#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import allure
import requests
from urllib.parse import urljoin
import logging

from requests import PreparedRequest, Response

logger = logging.getLogger("requests.session")
logging.basicConfig(level=logging.INFO)


class Session(requests.Session):
    """
    1. 支持BaseURL
    2. 支持日志记录
    """

    def __init__(self, base_url):
        super().__init__()  # 先按原有方式完成实例化
        self.base_url = base_url  # 再按新的方式完成额外操作

    @allure.step("发送请求")
    def request(self, method, url, *args, **kwargs):
        if not url.startswith("http"):  # 如果url不是以HTTP开头
            # 就自动添加baseurl
            url = urljoin(self.base_url, url)

        return super().request(method, url, *args, **kwargs)  # 按原有方式完成

    def send(self, request: PreparedRequest, *args, **kwargs) -> Response:
        logger.info(f"发送请求>>>>>>接口地址 = {request.method} {request.url}")
        logger.debug(f"发送请求>>>>>>请求头 = {request.headers}")
        logger.info(f"发送请求>>>>>>请求正文 = {request.body}")
        resp = super().send(request, **kwargs)  # 按原有方式发送请求

        logging.info(f"接收响应      <<<<<< 状态码 = {resp.status_code}")
        logging.debug(f"接收响应      <<<<<< 响应头 = {resp.headers}")
        logging.info(f"接收响应      <<<<<< 响应正文 = {resp.content}")

        return resp
